package com.jwm.client.soft;

import cn.hutool.json.JSONUtil;
import com.jwm.model.App;
import com.jwm.model.JarVo;
import com.jwm.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.MemoryUsage;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 崔洁
 */
@Component
public class JarTool {
    private static final Logger logger = LoggerFactory.getLogger(FileTool.class);

    public JarVo getInfo(App appVo) {
        logger.info("客户端 -> 获取Jar信息\n{}", JSONUtil.toJsonStr(appVo));
        JarVo jarVo = new JarVo();
        jarVo.setName(appVo.getName());
        jarVo.setPath(appVo.getPath());
        jarVo.setLogPath(appVo.getLogPath());
        jarVo.setTime(DateUtils.dateTimeNow());
        try {
            String jmxURL = "service:jmx:rmi:///jndi/rmi://localhost:" + appVo.getPort() + "/jmxrmi";
            JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
            Map<String, Object> auth = new HashMap<>();
            auth.put(JMXConnector.CREDENTIALS, new String[]{"cuijie", "cuijie1000"});
            JMXConnector connector = JMXConnectorFactory.connect(serviceURL, auth);
            MBeanServerConnection mbsc = connector.getMBeanServerConnection();

            Set MBeanset = mbsc.queryMBeans(null, null);
            // System.out.println("加载类数量 : " + MBeanset.size());
            jarVo.setBeanSize(MBeanset.size());
            // Iterator MBeansetIterator = MBeanset.iterator();
            // while (MBeansetIterator.hasNext()) {
            //     ObjectInstance objectInstance = (ObjectInstance) MBeansetIterator.next();
            //     ObjectName objectName = objectInstance.getObjectName();
            //     String canonicalName = objectName.getCanonicalName();
            //     System.out.println("canonicalName : " + canonicalName);
            // }

            // ObjectName name = new ObjectName("com.example:type=MyApp"); // 假设这是你的MBean名称
            // Object status = mbsc.getAttribute(name, "Status"); // 假设有一个名为Status的属性表示状态
            // System.out.println("Application status: " + status);

            //------------------------- system ----------------------
            ObjectName runtimeObjName = new ObjectName("java.lang:type=Runtime");
            // System.out.println("厂商:" + mbsc.getAttribute(runtimeObjName, "VmVendor"));
            // System.out.println("程序:" + mbsc.getAttribute(runtimeObjName, "VmName"));
            // System.out.println("版本:" + mbsc.getAttribute(runtimeObjName, "VmVersion"));
            Date starttime = new Date((Long) mbsc.getAttribute(runtimeObjName, "StartTime"));
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // System.out.println("启动时间:" + df.format(starttime));
            jarVo.setStartTime(df.format(starttime));
            Long timespan = (Long) mbsc.getAttribute(runtimeObjName, "Uptime");
            //System.out.println("连续工作时间:" + formatTimeSpan(timespan));
            jarVo.setTimeSpan(formatTimeSpan(timespan));
            //------------------------ JVM -------------------------
            //堆使用率
            ObjectName heapObjName = new ObjectName("java.lang:type=Memory");
            MemoryUsage heapMemoryUsage = MemoryUsage.from((CompositeDataSupport) mbsc.getAttribute(heapObjName, "HeapMemoryUsage"));
            long maxMemory = heapMemoryUsage.getMax();
            long commitMemory = heapMemoryUsage.getCommitted();
            long usedMemory = heapMemoryUsage.getUsed();
            long initMemory = heapMemoryUsage.getInit();
            // System.out.println("已使用的堆内存量: " + usedMemory / 1024 / 1024 + "M");
            // System.out.println("已提交的堆内存量: " + commitMemory / 1024 / 1024 + "M");
            // System.out.println("初始化的堆内存量: " + initMemory / 1024 / 1024 + "M");
            // System.out.println("堆内存的最大值: " + maxMemory / 1024 / 1024 + "M");
            // System.out.println("堆内存使用率:" + usedMemory * 100 / commitMemory + "%");
            jarVo.setUsedMemory(usedMemory / 1024 / 1024 + "M");
            jarVo.setCommitMemory(commitMemory / 1024 / 1024 + "M");
            jarVo.setPerMemory(usedMemory * 100 / commitMemory + "%");
            // MemoryUsage nonheapMemoryUsage = MemoryUsage.from((CompositeDataSupport) mbsc.getAttribute(heapObjName, "NonHeapMemoryUsage"));
            // long noncommitMemory = nonheapMemoryUsage.getCommitted();
            // long nonusedMemory = heapMemoryUsage.getUsed();
            // System.out.println("非堆内存使用率:" + nonusedMemory * 100 / noncommitMemory + "%");

            //----------------- Thread Pool ----------------
            ObjectName on = new ObjectName("java.lang:type=Threading");
            Integer threadCount = (Integer) mbsc.getAttribute(on, "ThreadCount");
            // System.out.println("线程数量: " + threadCount);
            jarVo.setCurrentThreadCount(threadCount);

            ObjectName osName = new ObjectName("java.lang:type=OperatingSystem");
            Object result = mbsc.getAttribute(osName, "SystemCpuLoad");
            // System.out.println("CPU负载信息: " + result);
            DecimalFormat ndf = new DecimalFormat("0.00");
            jarVo.setSystemCpuLoad(ndf.format(result));

            connector.close();
        } catch (Exception e) {
            // System.out.println("获取信息失败:" + appVo.getName());
            // logger.error("客户端 -> 获取Jar信息错误\n{}", e.getMessage());
            jarVo.setState(0);
            logger.info("客户端 -> 获取Jar信息失败");
            return jarVo;
        }
        logger.info("客户端 -> 获取Jar信息成功\n{}", JSONUtil.toJsonStr(jarVo));
        return jarVo;
    }

    public static String formatTimeSpan(long span) {
        long minseconds = span % 1000;

        span = span / 1000;
        long seconds = span % 60;

        span = span / 60;
        long mins = span % 60;

        span = span / 60;
        long hours = span % 24;

        span = span / 24;
        long days = span;
        return (new Formatter()).format("%1$d天 %2$02d:%3$02d:%4$02d.%5$03d", days, hours, mins, seconds, minseconds)
                .toString();
    }
}
